import { useLoginByPassword, useRegister } from '@/services/account';
import {
  AlipayOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProFormCaptcha,
  ProFormText,
} from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Divider, message, notification, Space, Switch, Tabs } from 'antd';
import { CSSProperties, useState } from 'react';

type LoginType = 'email' | 'account';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const tabItems = [
  { label: '账户密码登录', key: 'account' },
  { label: '手机号登录', key: 'mobile', disabled: true },
];

const Login: React.FC = () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const [email, setEmail] = useState<string>('123@qq.com');
  const [password, setPassword] = useState<string>('123456');
  const [isRegister, setIsRegister] = useState<boolean>(false);
  const { mutateAsync: loginByPassword } = useLoginByPassword(() =>
    history.back(),
  );
  const registerQuery = useRegister(email, password);

  const switchChange = (checked: boolean) => {
    setIsRegister(checked);
  };
  const onChange = (e: Record<string, any>) => {
    if (e.target.id === 'username') setEmail(e.target.value);
    if (e.target.id === 'password') setPassword(e.target.value);
  };
  const onLogin = async () => {
    if (isRegister) {
      const { data } = await registerQuery.refetch();
      if (data?.code === 200) {
        setIsRegister(false);
        notification.success({
          message: '注册成功，请登录',
        });
      } else if (data?.code === 1201) {
        message.error('邮箱已注册');
      } else {
        message.error('请检查账号和密码');
      }
    } else loginByPassword({ email, password });
  };
  return (
    <div
      style={{
        backgroundColor: 'white',
        height: 'calc(100vh - 48px)',
        margin: -24,
      }}
    >
      <LoginFormPage
        backgroundImageUrl="https://img1.baidu.com/it/u=3822418169,1183034242&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500"
        logo="https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg"
        title="APTW"
        subTitle="全村最好的农产品技术博客"
        initialValues={{ username: '123@qq.com', password: '123456' }}
        // activityConfig={{
        //   style: {
        //     boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
        //     color: '#fff',
        //     borderRadius: 8,
        //     backgroundColor: '#1677FF',
        //   },
        //   title: '拼多多入驻',
        //   subTitle: '猪肉大减价',
        //   action: (
        //     <Button
        //       size="large"
        //       style={{
        //         borderRadius: 20,
        //         background: '#fff',
        //         color: '#1677FF',
        //         width: 120,
        //       }}
        //     >
        //       去砍一刀
        //     </Button>
        //   ),
        // }}
        actions={
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              flexDirection: 'column',
            }}
          >
            <Divider plain>
              <span
                style={{ color: '#CCC', fontWeight: 'normal', fontSize: 14 }}
              >
                其他登录方式，尚未开通
              </span>
            </Divider>
            <Space align="center" size={24}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid #D4D8DD',
                  borderRadius: '50%',
                }}
              >
                <AlipayOutlined style={{ ...iconStyles, color: '#1677FF' }} />
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid #D4D8DD',
                  borderRadius: '50%',
                }}
              >
                <TaobaoOutlined style={{ ...iconStyles, color: '#FF6A10' }} />
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'column',
                  height: 40,
                  width: 40,
                  border: '1px solid #D4D8DD',
                  borderRadius: '50%',
                }}
              >
                <WeiboOutlined style={{ ...iconStyles, color: '#333333' }} />
              </div>
            </Space>
          </div>
        }
        onChange={(e) => onChange(e)}
        onFinish={() => onLogin()}
        // onChange={(e) => console.log(e)}
      >
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
          items={tabItems}
        ></Tabs>
        {loginType === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={'prefixIcon'} />,
              }}
              placeholder={'用户名/账号'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名/账号',
                },
              ]}
              onMetaChange={(r) => console.log(r)}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              placeholder={'密码：6位以上'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}
        {loginType === 'email' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={'prefixIcon'} />,
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={'prefixIcon'} />,
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                message.success('获取验证码成功！验证码为：1234');
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <Switch
            checkedChildren="注册"
            unCheckedChildren="登录"
            size="small"
            checked={isRegister}
            onChange={switchChange}
          />
          <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default Login;
